package com.meitianhui.convenitenbuy.module.wallet.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.WriterException;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.wallet.contract.WalletPaymentContract;
import com.meitianhui.convenitenbuy.module.wallet.di.DaggerWalletComponent;
import com.meitianhui.convenitenbuy.module.wallet.di.WalletModule;
import com.meitianhui.convenitenbuy.module.wallet.model.PaymentCodeBean;
import com.meitianhui.convenitenbuy.module.wallet.model.UsableChangeBean;
import com.meitianhui.convenitenbuy.module.wallet.presenter.WalletPaymentPresenter;
import com.meitianhui.convenitenbuy.push.model.PushBean;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxTimerUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.ZXingUtils;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class WalletPaymentActivity extends BaseToolbarActivity implements WalletPaymentContract.View {
    private DisplayMetrics dm2;
    private int width = 0;
    TextView mTvPaymentCode1;
    TextView mTvPaymentCode2;
    TextView mTvPaymentCode3;
    TextView mTvPaymentCode4;
    TextView mTvAsset;
    ImageView mIvBarCode;
    ImageView mIvQRCode;
    RxTimerUtils mRx;

    @Inject
    WalletPaymentPresenter mPresenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setTbTitle(getString(R.string.wallet_payment_code));
        setTbMenu(getString(R.string.wallet_payment_setting));
        DaggerWalletComponent.builder().appComponent(App.getInstance().getAppComponent()).walletModule(new WalletModule(this)).build().inject(this);
        dm2 = getResources().getDisplayMetrics();
        WindowManager wm = this.getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        mRx = new RxTimerUtils();
        initId();
        initInfo();
        isEnable(false);
        initTimer();
        registerPush();
    }

    private void registerPush() {
        Disposable disposable = RxBus.get().toFlowable(PushBean.class).subscribe(new Consumer<PushBean>() {
            @Override
            public void accept(PushBean payResultBean) throws Exception {
                if (payResultBean != null && payResultBean.getType().equals(Constants.PUSH_TYPE_SCAN_PAY_SUCCESS)) {
                    SystemUtils.vibrate(WalletPaymentActivity.this, new long[]{100, 400}, -1);
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));
                    finish();
                }
            }
        });

        Disposable disposable1 = RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean payResultBean) throws Exception {
                if (payResultBean != null && payResultBean.getType() == Constants.EVENT_TYPE_FINISH)
                    finish();
            }
        });

        mCompositeDisposable.add(disposable);
        mCompositeDisposable.add(disposable1);
    }

    @Override
    protected int setView() {
        return R.layout.activity_wallet_payment;
    }

    private void initId() {
        mTvPaymentCode1 = getViewById(R.id.tv_wallet_payment_code1);
        mTvPaymentCode2 = getViewById(R.id.tv_wallet_payment_code2);
        mTvPaymentCode3 = getViewById(R.id.tv_wallet_payment_code3);
        mTvPaymentCode4 = getViewById(R.id.tv_wallet_payment_code4);
        mTvAsset = getViewById(R.id.tv_wallet_payment_asset);
        mIvBarCode = getViewById(R.id.iv_wallet_payment_bar_code);
        mIvQRCode = getViewById(R.id.iv_wallet_payment_qr_code);
    }

    /**
     * 获取用户付款码
     */
    private void initInfo() {
        mPresenter.getUsableChange();
        mPresenter.getUserSecurityCode();
    }

    @Override
    protected void clickMenu() {
        Intent intent = new Intent(this, WalletPaymentSettingActivity.class);
        startActivity(intent);
    }

    @Override
    public void getUsableBalanceBack(UsableChangeBean bean) {
        mTvAsset.setText(
                getString(R.string.wallet_payment_usable) +
                        (bean == null ? getString(R.string.wallet_zero_decimal)
                                : (TextUtils.isEmpty(bean.getUsable_cash_balance()) ?
                                        getString(R.string.wallet_zero_decimal) : bean.getUsable_cash_balance())));
    }

    @Override
    public void getSecurityCodeBack(PaymentCodeBean bean) {
        if (bean != null && (bean.getSecurity_code() != null)) {
            String securityCode = bean.getSecurity_code();
            showSecurityCode(securityCode);
            showBarCode(securityCode);
            showQRCode(securityCode);
        }
    }

    /**
     * 显示用户付款码
     *
     * @param securityCode
     */
    private void showSecurityCode(String securityCode) {
        if (securityCode.length() > 12) {
            mTvPaymentCode1.setText(securityCode.substring(0, 4));
            mTvPaymentCode2.setText(securityCode.substring(4, 8));
            mTvPaymentCode3.setText(securityCode.substring(8, 12));
            mTvPaymentCode4.setText(securityCode.substring(12, securityCode.length()));
        }
    }

    /**
     * 显示二维码
     *
     * @param securityCode
     */
    private void showQRCode(String securityCode) {
        try {
            mIvQRCode.setImageBitmap(ZXingUtils.createQRCode(securityCode, 200));
            Animation a = AnimationUtils.loadAnimation(this, R.anim.zoom_in);
            mIvQRCode.setAnimation(a);
        } catch (WriterException e) {
            LogUtils.e("create QR code fail.");
        }
    }

    /**
     * 显示条形码
     *
     * @param securityCode
     */
    private void showBarCode(String securityCode) {
        try {
            mIvBarCode.setImageBitmap(ZXingUtils.createOneDCode(securityCode, width, (int) (102 * dm2.density)));
            Animation a = AnimationUtils.loadAnimation(this, R.anim.zoom_in);
            mIvBarCode.setAnimation(a);
        } catch (WriterException e) {
            LogUtils.e("create bar code fail.");
        }
    }

    private void initTimer() {
        RxTimerUtils.IRxNext next = new RxTimerUtils.IRxNext() {

            @Override
            public void doNext(long number) {
                initInfo();
            }
        };
        mRx.interval(60000, next);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SystemUtils.vibrateCancel(WalletPaymentActivity.this);
        mRx.cancel();
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    protected void onRefreshData() {

    }
}
